<template>
  <div class="home">
    <el-row :gutter="24">
      <el-col :span="24">
        <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
          @select="handleSelect"
        >
          <el-menu-item index="3">高伟达加班费用报销</el-menu-item>
        </el-menu>
        <div class="line"></div>
        <div style="margin-top: 20px">
          <el-time-select
            v-model="value"
            :picker-options="{ start: '08:30', step: '00:30', end: '24:00' }"
            placeholder="选择时间"
            style="float: left"
          ></el-time-select>
          <el-upload
            class="upload-demo"
            action
            :on-change="handleChange"
            :show-file-list="false"
            :auto-upload="false"
            style="margin-left: 15px; float: left"
          >
            <el-button
              size="medium"
              type="primary"
              style="margin-bottom: 15px; float: left"
              >上传打卡记录</el-button
            >
          </el-upload>
          <el-upload
            class="upload-demo"
            action
            :on-change="handleChangeOne"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            :limit="30"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :auto-upload="false"
          >
            <el-button size="small" type="primary">上传工时表</el-button>
          </el-upload>
          
          <!-- <el-button @click="setCurrent(tableData[1])">选中第二行</el-button>-->
          <!-- <el-button @click="down()">导出</el-button> -->
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="12">
      <el-col :span="12">
        <el-card shadow="always"
          ><ul>
            <li>默认加班时间：20:30，如需修改默认加班时间点击上述时间组件。</li>
            <li>周一到周五按照时间组件计算是否加班，周六周日打卡即算加班</li>
            <li>单个excle每天的加班人数不能超过30人</li>
            <li>
              如果不能上传文件，可能是浏览器不兼容，请使用最新版火狐、谷歌浏览器
            </li>
            <li>
              工时表名称以“项目编号#”开头。如：190777-96#XD软件序列考勤表 (32).xls
            </li>
          </ul>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import XLSX from "xlsx";
import style from "../style";
import XLSXStyle from "xlsx-style";
import {
  getAllDate,
  overtime,
  overtimeWeekend,
  jsono,
  format,
  jsono1,
  changeWeek,
} from "../util";
export default {
  data() {
    return {
      currentRow: null,
      value: "20:30",
      activeIndex: "",
      outList: [], //输出到excle的集合
      month: 1,
      fileList: [],
      jsono:[],
      projectNum: "", //项目编号
      WorkingCycle:[],//考勤周期
      count:[]
    };
  },
  created() {
    this.ccc();
  },
  computed: {
    filename: function () {
      return `${this.projectNum}#${this.month}月加班费用报销明细表2.xlsx`;
    },
  },
  methods: {
    handleChangeOne(files, fileList) {
      console.log(files);
      console.log(files.name.split("#")[0]);
      console.log(fileList);
      this.projectNum = files.name.split("#")[0]//获取项目编号

      jsono1[0].列头5 = this.projectNum//修改jsono1项目编号
      jsono1[1].列头5 = this.projectNum//修改jsono1项目编号
      jsono1[2].列头5 = this.projectNum//修改jsono1项目编号
      const reader = new FileReader();
      reader.readAsArrayBuffer(files.raw);
      reader.onload = () => {
        const buffer = reader.result;
        const bytes = new Uint8Array(buffer);
        const length = bytes.byteLength;
        let binary = "";
        for (let i = 0; i < length; i++) {
          binary += String.fromCharCode(bytes[i]);
        }
        const wb = XLSX.read(binary, {
          type: "binary",
        });
        const outdata = XLSX.utils.sheet_to_json(wb.Sheets["XD软件序列考勤表"]);
        this.data = [...outdata];
        console.log(outdata);
        //组装数据   { "2020-12-21": ["田晓旗","姜冬东", "aaa"] ,"2020-12-22": ["呼文梅","姜冬东", "aaa"]};
        let wokingData = {"2020-12-21": ["田晓旗","姜冬东", "aaa"] ,"2020-12-22": ["呼文梅","姜冬东", "aaa"]};//本项目打卡的人
        let WorkingCycle = this.WorkingCycle//考勤周期
        for(let cIndex in WorkingCycle){
          wokingData[`${WorkingCycle[cIndex]}`] = []
        }
        let gsColList = []//工时表列名数组  ["__EMPTY", "__EMPTY_1", "__EMPTY_2"]
        outdata.forEach((val ,index) => {
          console.log(val,index);//{__EMPTY: 1, __EMPTY_1: "侯梦飞-00010733", __EMPTY_2: 10, __EMPTY_3: 10, __EMPTY_4: 10,}
         if(index == 0){
           gsColList = Object.keys(val)
         }

          if(index%2==0 && index > 0){
            let nameNUm = val.__EMPTY_1 ; let nameList = nameNUm.split("-") ; let name = nameList[0];
            gsColList.forEach((gsVal,gsindex )=> {
              console.log(gsVal,gsindex)
              if(gsindex>=2){
                console.log(val[gsVal])
                console.log(WorkingCycle[gsindex - 2])            
                if(val[gsVal]){
                  wokingData[`${WorkingCycle[gsindex - 2]}`].push(name)
                }
              }

            })
          }
          


        });
        console.log(wokingData)

      //  wokingData = {"2020-12-21": ["田晓旗","姜冬东", "aaa"] ,"2020-12-22": ["呼文梅","姜冬东", "aaa"]};
        // return 
        let working = []//本项目加班的人 {"2020-12-21":["田晓旗"]},{"2020-12-22":["郭鹏程"]}
        jsono.forEach((val, index) => {
          //抽取项目编号的数据
          if (index >= 6) {
            // console.log(val);
            //获取日期
            let DayWorking = wokingData[`${val["项目组__12__月份加班考勤表（加班至晚9点以后）"]}`]; //某一天加班的人
            // console.log(DayWorking);
            if (DayWorking) {//当天有填工时
              Object.keys(val).forEach((n) => {
               
                let findName = DayWorking.find((name) => {
                  //true  今天加班并且属于项目
                  // console.log( val[n],name)
                  return val[n] == name;
                });

                if(findName){
                  console.log(DayWorking)
                  console.log(working[`${val["项目组__12__月份加班考勤表（加班至晚9点以后）"]}`])
                  let date = val["项目组__12__月份加班考勤表（加班至晚9点以后）"] // 打卡日期
                  console.log(date)
                  if(!working[`${date}`]){
                    working[`${date}`] = []
                    let week = changeWeek(new Date(date).getDay())//添加星期几
                    console.log(week)
                    working[`${date}`].push(week)
                  }
                  working[`${date}`].push(findName)
                  
                }

              });
            }
          }
        });

        console.log(working)
        let d = 0
        for(let workingKey in working){
          console.log(workingKey)
          if (working[workingKey].length > 31) {
            this.$message({
              message: "单个excle每天的加班人数不能超过30人",
              type: "warning",
            });
            return;
          }
          console.log(d)
          if(working[workingKey][0]){ }



          let line1 = {
            "项目组__12__月份加班考勤表（加班至晚9点以后）": workingKey,
            列头2: working[workingKey][0],
            列头3: `=COUNTA(E${d * 3 + 8}:N${d * 3 + 10})`,
            列头4: `=C${d * 3 + 8}*20`,
            列头5: working[workingKey][1],
            列头6: working[workingKey][2],
            列头7: working[workingKey][3],
            列头8: working[workingKey][4],
            列头9: working[workingKey][5],
            列头10: working[workingKey][6],
            列头11: working[workingKey][7],
            列头12: working[workingKey][8],
            列头13: working[workingKey][9],
            列头14: working[workingKey][10],
          };
          let line2 = {
            "项目组__12__月份加班考勤表（加班至晚9点以后）": workingKey,
            列头2: working[workingKey][0],
            列头3: "=COUNTA(E8:N10)",
            列头4: "=C8*20",
            列头5: working[workingKey][11],
            列头6: working[workingKey][12],
            列头7: working[workingKey][13],
            列头8: working[workingKey][14],
            列头9: working[workingKey][15],
            列头10: working[workingKey][16],
            列头11: working[workingKey][17],
            列头12: working[workingKey][18],
            列头13: working[workingKey][19],
            列头14: working[workingKey][20],
          };
          let line3 = {
            "项目组__12__月份加班考勤表（加班至晚9点以后）": workingKey,
            列头2: working[workingKey][0],
            列头3: "=COUNTA(E8:N10)",
            列头4: "=C8*20",
            列头5: working[workingKey][21],
            列头6: working[workingKey][22],
            列头7: working[workingKey][23],
            列头8: working[workingKey][24],
            列头9: working[workingKey][25],
            列头10: working[workingKey][26],
            列头11: working[workingKey][27],
            列头12: working[workingKey][28],
            列头13: working[workingKey][29],
            列头14: working[workingKey][30],
          };
          d = d +1
          jsono1.push(line1);
          jsono1.push(line2);
          jsono1.push(line3);

          
        }
        let count = this.count
        for (let as in count) {
          jsono1.push(count[as]);
        }


      console.log(jsono1)
      this.downloadExl(jsono1);

      };
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 30 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    down(data) {
      //数据，一定注意需要时二维数组
      console.log("aaa");
      var filename = "190777-53#12月加班费用报销明细表2.xlsx"; //文件名称
      var ws_name = "加班餐费的具体加班几天名单"; //Excel第一个sheet的名称
      var wb = XLSX.utils.book_new(),
        ws = XLSX.utils.aoa_to_sheet(data);
      XLSX.utils.book_append_sheet(wb, ws, ws_name); //将数据添加到工作薄
      XLSX.writeFile(wb, filename); //导出Excel
    },
    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row);
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    handleSelect() {},
    handleOne() {},
    handleChange(file, fileList) {
      console.log(file);
      console.log(fileList);
      const reader = new FileReader();
      reader.readAsArrayBuffer(file.raw);
      reader.onload = () => {
        const buffer = reader.result;
        const bytes = new Uint8Array(buffer);
        const length = bytes.byteLength;
        let binary = "";
        for (let i = 0; i < length; i++) {
          binary += String.fromCharCode(bytes[i]);
        }
        const wb = XLSX.read(binary, {
          type: "binary",
        });
        const outdata = XLSX.utils.sheet_to_json(wb.Sheets["考勤记录"]);
        this.data = [...outdata];
        console.log(outdata);

        let startdate = this.data[0].__EMPTY_1.split(" ~ ")[0]; //起始日期
        let enddate = this.data[0].__EMPTY_1.split(" ~ ")[1]; //结束日期
        //设置月份同步文件名称
        this.month = startdate.split("-")[1];
        console.log(startdate);
        let dateArr = getAllDate(startdate, enddate); //考勤周期
        console.log(dateArr);

        this.WorkingCycle = dateArr ;//考勤周期
        for (var f = 0; f < dateArr.length; f++) {
          let aa = [dateArr[f], new Date(dateArr[f]).getDay()]; //"2020-12-01" 星期六
          this.outList.push(aa);
        }
        console.log(this.outList);
        let step = 1;
        let list = []; //获取姓名集合
        this.data.map((v) => {
          if (v.__EMPTY_7 == "姓 名:") {
            list.push(step);
          }
          step = step + 1;
        });
        let dakaList = []; //获取打卡同事的index
        for (var i = 0; i < list.length; i++) {
          let j = i + 1;
          if (list[j] == list[i] + 1) {
            this;
          } else {
            dakaList.push(list[i]);
          }
        }
        //组装keys模板（）
        let keys = [];
        for (let dateAIndex = 0; dateAIndex < dateArr.length; dateAIndex++) {
          if (dateAIndex == 0) {
            keys.push("考 勤 记 录 表");
          }
          if (dateAIndex == 1) {
            keys.push("__EMPTY");
          } else if (dateAIndex > 1) {
            // console.log(dateAIndex - 1);
            keys.push(`__EMPTY_${dateAIndex - 1}`);
          }
        }
        console.log(keys);

        let workData = []; //打卡信息二维数组
        //处理打卡同事的数据 dakaList有记录的index
        for (var o = 0; o < dakaList.length; o++) {
          let index = 0;
          let val = []; //组装打卡信息 [name , time1 , time2]
          let name = this.data[dakaList[o] - 1].__EMPTY_9;
          val.push(name);
          val.push(this.data[dakaList[o]]); //打卡时间记录
          workData.push(val);
        }
        console.log(workData);
        //记录加班次数
        let count = [];
        let countObj = {};
        //遍历 workData 判断是否加班
        for (let ind = 0; ind < workData.length; ind++) {
          for (let key = 0; key < keys.length; key++) {
            // console.log(this.outList[key]);
            let contime = workData[ind][1][keys[key]]; //获取时间
            let adudje = 0;
            if (this.outList[key][1] == 0 || this.outList[key][1] == 6) {
              //如果是周六日
              adudje = overtimeWeekend(contime);
            } else {
              adudje = overtime(
                contime,
                this.value.split(":")[0] + this.value.split(":")[1]
              ); //判断函数
            }
            if (adudje == 1) {
              //获取名称
              this.outList[key].push(workData[ind][0]);
              let name = workData[ind][0];
              if (!countObj[name]) {
                countObj[name] = 1;
              } else {
                countObj[name]++;
              }
            }
          }
        }
        count.push([]);
        count.push([]);
        count.push([]);
        Object.keys(countObj).forEach((val, index) => {
          let element = {
            "项目组__12__月份加班考勤表（加班至晚9点以后）": "",
            列头2: "",
            列头3: "",
            列头4: "",
            列头5: "",
            列头6: `${index + 1}`,
            列头7: `${val}`,
            列头8: countObj[val],
            列头9: "",
            列头10: "",
            列头11: "",
            列头12: "",
            列头13: "",
            列头14: "",
          };
          console.log(element);

          count.push(element);
        });


        console.log(this.outList);
        // this.down(this.outList);
        //修改星期 时间格式
        for (let d in this.outList) {
          this.outList[d][1] = changeWeek(this.outList[d][1]);
        }
        //转化数据this.outList=> jsono
        console.log(jsono);

        //修改项目号

        for (let d in this.outList) {
          if (this.outList[d].length > 32) {
            this.$message({
              message: "单个excle每天的加班人数不能超过30人",
              type: "warning",
            });
            return;
          }
          //转化数据 0*3 + 8     8 11 14
          let line1 = {
            "项目组__12__月份加班考勤表（加班至晚9点以后）": this.outList[d][0],
            列头2: this.outList[d][1],
            列头3: `=COUNTA(E${d * 3 + 8}:N${d * 3 + 10})`,
            列头4: `=C${d * 3 + 8}*20`,
            列头5: this.outList[d][2],
            列头6: this.outList[d][3],
            列头7: this.outList[d][4],
            列头8: this.outList[d][5],
            列头9: this.outList[d][6],
            列头10: this.outList[d][7],
            列头11: this.outList[d][8],
            列头12: this.outList[d][9],
            列头13: this.outList[d][10],
            列头14: this.outList[d][11],
          };
          let line2 = {
            "项目组__12__月份加班考勤表（加班至晚9点以后）": this.outList[d][0],
            列头2: this.outList[d][1],
            列头3: "=COUNTA(E8:N10)",
            列头4: "=C8*20",
            列头5: this.outList[d][12],
            列头6: this.outList[d][13],
            列头7: this.outList[d][14],
            列头8: this.outList[d][15],
            列头9: this.outList[d][16],
            列头10: this.outList[d][17],
            列头11: this.outList[d][18],
            列头12: this.outList[d][19],
            列头13: this.outList[d][20],
            列头14: this.outList[d][21],
          };
          let line3 = {
            "项目组__12__月份加班考勤表（加班至晚9点以后）": this.outList[d][0],
            列头2: this.outList[d][1],
            列头3: "=COUNTA(E8:N10)",
            列头4: "=C8*20",
            列头5: this.outList[d][22],
            列头6: this.outList[d][23],
            列头7: this.outList[d][24],
            列头8: this.outList[d][25],
            列头9: this.outList[d][26],
            列头10: this.outList[d][27],
            列头11: this.outList[d][28],
            列头12: this.outList[d][29],
            列头13: this.outList[d][30],
            列头14: this.outList[d][31],
          };
          jsono.push(line1);
          jsono.push(line2);
          jsono.push(line3);
        }
        for (let as in count) {
          jsono.push(count[as]);
        }
        this.count = count
        // jsono[]
        console.log(jsono);
        for (let jsonoindex in jsono) {
          if (jsonoindex > 6) {
            for (let v in jsono[jsonoindex]) {
              if (!jsono[jsonoindex][v]) {
                delete jsono[jsonoindex][v];
              }
            }
          }
        }
        console.log(jsono);
        this.jsono = jsono;
        // this.downloadExl(jsono);
      };
    },
    downloadExl(json, type) {
      var tmpdata = json[0];
      json.unshift({});
      var keyMap = []; //获取keys
      for (var k in tmpdata) {
        keyMap.push(k);
        json[0][k] = k;
      }
      var tmpdata = []; //用来保存转换好的json
      json
        .map((v, i) =>
          keyMap.map((k, j) =>
            Object.assign(
              {},
              {
                v: v[k],
                position:
                  (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) +
                  (i + 1),
              }
            )
          )
        )
        .reduce((prev, next) => prev.concat(next))
        .forEach(
          (v, i) =>
            (tmpdata[v.position] = {
              v: v.v,
            })
        );

      var outputPos = Object.keys(tmpdata); //设置区域,比如表格从A1到D10
      console.log(tmpdata);
      //设置单元格合并
      for (let ad = 1; ad <= (json.length - 6) / 3; ad++) {
        let f1 = {
          s: {
            c: 0,
            r: (ad - 1) * 3 + 7,
          },
          e: {
            c: 0,
            r: (ad - 1) * 3 + 9,
          },
        };
        let f2 = {
          s: {
            c: 1,
            r: (ad - 1) * 3 + 7,
          },
          e: {
            c: 1,
            r: (ad - 1) * 3 + 9,
          },
        };
        let f3 = {
          s: {
            c: 2,
            r: (ad - 1) * 3 + 7,
          },
          e: {
            c: 2,
            r: (ad - 1) * 3 + 9,
          },
        };
        let f4 = {
          s: {
            c: 3,
            r: (ad - 1) * 3 + 7,
          },
          e: {
            c: 3,
            r: (ad - 1) * 3 + 9,
          },
        };
        style.merges.push(f1);
        style.merges.push(f2);
        style.merges.push(f3);
        style.merges.push(f4);
        //设置A8--D8样式
        tmpdata[`A${(ad - 1) * 3 + 8}`].s = style.font3;
        tmpdata[`B${(ad - 1) * 3 + 8}`].s = style.font3;
        tmpdata[`C${(ad - 1) * 3 + 8}`].s = style.font3;
        tmpdata[`D${(ad - 1) * 3 + 8}`].s = style.font3;
        //设置姓名区域样式
        let list = ["E", "F", "G", "H", "I", "J", "K", "L", "M", "N"];
        for (let indexList in list) {
          console.log(tmpdata[`${list[indexList]}${(ad - 1) * 3 + 10}`]);

          tmpdata[`${list[indexList]}${(ad - 1) * 3 + 8}`].s = style.font4;
          tmpdata[`${list[indexList]}${(ad - 1) * 3 + 9}`].s = style.font4;
          if (tmpdata[`${list[indexList]}${(ad - 1) * 3 + 10}`]) {
            tmpdata[`${list[indexList]}${(ad - 1) * 3 + 10}`].s = style.font4;
          }
        }
      }
      tmpdata["!merges"] = style.merges; //设置单元格合并
      tmpdata["A1"].s = style.title;
      tmpdata["A4"].s = tmpdata["B4"].s = tmpdata["D4"].s = tmpdata["E4"].s =
        style.font1;
      tmpdata["A5"].s = tmpdata["F5"].s = tmpdata["K5"].s = style.font2;
      tmpdata["A7"].s = tmpdata["B7"].s = tmpdata["C7"].s = tmpdata[
        "D7"
      ].s = tmpdata["E7"].s = style.font3;
      console.log(tmpdata);

      var tmpWB = {
        SheetNames: ["加班餐费的具体加班几天名单"], //保存的表标题
        Sheets: {
          加班餐费的具体加班几天名单: Object.assign(
            {},
            tmpdata, //内容
            {
              "!ref": outputPos[0] + ":" + outputPos[outputPos.length - 1], //设置填充区域
            }
          ),
        },
      };
      var tmpDown = new Blob(
        [
          this.s2ab(
            XLSXStyle.write(
              tmpWB,
              {
                bookType: type == undefined ? "xlsx" : type,
                bookSST: false,
                type: "binary",
              } //这里的数据是用来定义导出的格式类型
            )
          ),
        ],
        {
          type: "",
        }
      );
      this.saveAs(tmpDown, this.filename);
    },
    getCharCol(n) {
      (s = ""), (m = 0);
      while (n > 0) {
        m = (n % 26) + 1;
        s = String.fromCharCode(m + 64) + s;
        n = (n - m) / 26;
      }
      return s;
    },
    s2ab(s) {
      if (typeof ArrayBuffer !== "undefined") {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      } else {
        var buf = new Array(s.length);
        for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff;
        return buf;
      }
    },
    saveAs(obj, fileName) {
      var tmpa = document.createElement("a");
      tmpa.download = fileName || "下载";
      tmpa.href = URL.createObjectURL(obj);
      tmpa.click();
      setTimeout(function () {
        URL.revokeObjectURL(obj);
      }, 100);
    },
    ccc() {
      let j = { a: 1, b: 2 };
      Object.keys(j).forEach((ind, ele) => {
        console.log(ele);
      });
    },
  },
};
</script>